<!--
    参数 ：
    loanBackPeasonParams{applyNo,contractNo,taskId}    Object  请求参数 必须
    loanBackReasonVisible    Boolean   初始化请求 必需
-->

<template>
    <Modal v-model="loanBackReasonVisible" scrollable :title="this.modalTitle" :closable="false" :mask-closable='false' :width="1000" :styles="{top: '180px'}">
        <div slot="footer">
            <Spin size="large" fix v-if="spinShow"></Spin>
            <Button type="text" @click="backBtn">关闭</Button>
            <Button type="primary" @click="saveBtn">保存</Button>
            <Button type="primary" @click="submitCheck">提交</Button>
        </div>
        <Row>
            <Form ref="searchForm" :model="searchForm" inline>
                <div>
                    <Card :styles="{overflow:'hidden', hight:'400px'}">
                        <FormItem
                            v-for="(item, index) in searchForm.items"
                            v-if="item.status"
                            :key="index">
                            <Row>
                                <Col span="2">
                                    <label>文件类型</label>
                                </Col>
                                <Col span="6">
                                    <Select v-model="item.fileType" filterable clearable placeholder="请选择" style="width:180px" @on-change="handleChange(item.fileType,index)">
                                        <Option v-for="item in fileTypeNameData" :label="item.attachmentName" :value="item.attachmentId" :key="item.attachmentName">{{item.attachmentName}}</Option>
                                    </Select>
                                </Col>
                                <Col span="2">
                                    <label>退回话术</label>
                                </Col>
                                <Col span="11">
                                    <Select v-model="item.backWordsList"
                                            filterable
                                            clearable
                                            placeholder="请选择"
                                            multiple
                                            style="width:360px"
                                            @on-change="changeBackWords(item.backWordsList,index)"
                                            ref="backWordsSelect">
                                        <Option v-for="itm in backWordsData[index]" :label="itm.backWords" :value="itm.backWordsValue" :key="itm.backWords">{{itm.backWords}}</Option>
                                    </Select>
                                </Col>
                                <Col span="3">
                                    <Button @click="addBtn" type="info">新增</Button>
                                    <Button @click="delBtn(index)" v-if="index!=0" type="info">删除</Button>
                                    <Button @click="delBtn(index)" v-if="index == 0 && item.id!=undefined && item.id!=null && item.id!=''" type="info">删除</Button>
                                </Col>
                            </Row>
                            <Row>
                                <Col span="2">
                                    <label>问题描述</label>
                                </Col>
                                <Col span="20">
                                    <Input type="textarea" v-model="item.backWords" clearable placeholder="请输入"
                                           style="width: 800px"/>
                                </Col>
                            </Row>
                        </FormItem>
                    </Card>
                </div>
            </Form>
        </Row>
    </Modal>
</template>

<script>
    import {
        getBackPartnersList,
        getFileTypeList,
        editBackPartner,
        saveBackPartner,
        deleteBackPartner,
        getBackWords,
        saveOrUpdateBackResonList,
        getBackDescList,
        submitBackToPartners} from '_p/basic/api/image/loanBackReason'
    import {getByTypes} from '_p/basic/api/admin/datadic'
    export default {
        name: "loanBackReason",
        props: {
            loanBackReasonVisible: {
                type: Boolean,
                default: false,
            },
            loanBackReasonParam: {
                type: Object,
            },
            loanBaseData: {
                type: Array,
            }
        },
        data() {
            return {
                loading: true,
                spinShow: false,
                modalTitle: "退回经销商原因",
                dicKeys: [
                    'caseFileType',
                    'businessType'
                ],
                dataDic: {},
                columns: [
                    {
                        title: "文件类型",
                        key: "fileTypeName",
                        sortable: true,
                    },
                    {
                        title: "问题描述",
                        key: "backWords",
                        sortable: true,
                    },
                    {
                        title: "操作",
                        key: "action",
                        align: "center",
                        slot: "action",
                        className: 'select-table-info-column'
                    },
                ],
                data: [],
                saveVisible: false,
                fileTypeNameData: [],
                backWordsData: [],
                total: 0,
                loanBackReasonParams: {
                    pageSize: 5,
                    pageNumber: 1
                },
                searchBackWordsFrom: {
                    attachmentId: '',
                },
                index: 1,
                searchForm: {
                    items: [
                        {
                            id: '',
                            fileTypeName: '',
                            fileType: '',
                            backWords: '',
                            index: 1,
                            status: 1
                        }
                    ]
                },
            }
        },
        watch: { //深度 watcher
            loanBackReasonVisible(val) {
                if (val) {
                    this.init()
                }
            }
        },
        mounted() {
            this.init();
            console.log(this.loanBackReasonParam,'this.LoanBackReasonParam')
        },
        methods: {
            init() {
                if (this.loanBackReasonVisible) {
                    this.loanBackReasonParams.applyNo = this.loanBackReasonParam.belongNo;
                    this.loanBackReasonParams.contractNo = this.loanBackReasonParam.busiNo;
                    this.loanBackReasonParams.taskId = this.loanBackReasonParam.taskId;
                    this.getFileTypeList();
                    this.getBackPartnersList();
                    this.initDataDic()
                }
            },
            initDataDic() {
                let self = this
                getByTypes(this.dicKeys).then(res => {
                    if (res.code === '0000' && res.data) {
                        self.dataDic = res.data
                    }
                })
            },
            handleChange(value, index) {
                this.searchBackWordsFrom.attachmentId = value;
                getBackWords(this.searchBackWordsFrom).then(res => {
                    res.data.forEach(clounm => {
                        clounm.backWordsValue = clounm.id + "," + clounm.backWords;
                    })
                    this.backWordsData.splice(index, 1, res.data)
                })
            },
            getFileTypeList() {
                let params = [];

                getFileTypeList(this.loanBackReasonParams).then(res => {
                    params = res.data;
                    params.forEach(params => {
                        this.loanBaseData.forEach(vo => {
                            if (vo.attachmentCode == params.attachmentId) {
                                this.fileTypeNameData.push(params)
                            }
                        })
                    })
                })
            },
            getBackPartnersList() {
                getBackPartnersList(this.loanBackReasonParams).then(res => {
                    if (res.data.length != 0) {
                        let data = '';
                        for (let i = 0; i < res.data.length; i++) {
                            res.data[i].index = i + 1;
                            res.data[i].status = 1;
                            if (res.data[i].backDesc != undefined && res.data[i].backDesc != '') {
                                res.data[i].backWordsList = res.data[i].backDesc.split(';');
                            }
                            this.searchForm.items.splice(i, 1, res.data[i])
                            this.backWordsData.splice(i, 1, [])
                            data += res.data[i].fileType + ','
                        }
                        getBackDescList(data).then(res => {
                            for (let j = 0; j < res.data.length; j++) {
                                res.data[j].forEach(clounm => {
                                    clounm.backWordsValue = clounm.id + "," + clounm.backWords;
                                })
                                this.backWordsData.splice(j, 1, res.data[j])
                            }
                        })
                        let item = {
                            id: '',
                            fileTypeName: '',
                            fileType: this.loanBackReasonParam.fileType,
                            backWords: '',
                            index: res.data.length + 1,
                            status: 1
                        }
                        this.searchForm.items.splice(res.data.length, 1, item)
                        this.handleChange(this.loanBackReasonParam.fileType, res.data.length)
                    } else {
                        this.searchForm = {
                            items: [
                                {
                                    id: '',
                                    fileTypeName: '',
                                    fileType: this.loanBackReasonParam.fileType,
                                    backWords: '',
                                    index: 1,
                                    status: 1
                                }
                            ]
                        }
                        this.handleChange(this.loanBackReasonParam.fileType, 0)
                    }
                })
            },
            delBtn(val) {
                if (this.searchForm.items[val].id != undefined && this.searchForm.items[val].id != null && this.searchForm.items[val].id != '') {
                    deleteBackPartner(this.searchForm.items[val]).then(res => {
                        this.$Message.success("删除成功！");
                        this.$emit("getFileList");
                    })
                }
                this.searchForm.items.splice(val, 1);
                this.backWordsData.splice(val, 1)
                if (this.searchForm.items.length == 0) {
                    this.$emit('closepop');
                }
            },
            editBtn(val) {
                this.searchForm = val;
                this.searchForm.id = val.id;
                this.saveVisible = true;
            },
            addBtn() {
                this.index++;
                this.searchForm.items.push({
                    value: '',
                    index: this.index,
                    status: 1
                });
                this.backWordsData.splice(this.index, 1, [])
            },
            saveBtn() {
                let params = true;
                this.searchForm.items.forEach(item => {
                    if (item.fileType != undefined && item.fileType != null && item.fileType != '' &&
                        item.backWords != undefined && item.backWords != null && item.backWords != '') {
                    } else {
                        params = false;
                    }
                })
                if (params) {
                    this.$refs.searchForm.validate(valid => {
                        if (valid) {
                            this.searchForm.items.forEach(item => {
                                if (item.id != '' && item.id != null && item.id != undefined && item.id != null && item.id != '') {
                                    editBackPartner(item).then(res => {
                                        if (res.code === '0000') {
                                        }
                                    })
                                } else {
                                    item.applyNo = this.loanBackReasonParams.applyNo;
                                    item.contractNo = this.loanBackReasonParams.contractNo;
                                    item.taskId = this.loanBackReasonParams.taskId;
                                    saveBackPartner(item).then(res => {
                                        if (res.code === '0000') {
                                        }
                                    })
                                }
                            })
                            // this.searchForm.items=[]
                            // this.fileTypeNameData=[]
                            // this.backWordsData=[]
                            setTimeout(() => {
                                this.$Message.success("保存成功！");
                                this.$emit('getFileList');
                                this.backBtn();
                            }, 300);
                        }
                    })
                } else {
                    this.$Message.warning("包含未选择的文件类型，未填写的退回话术！")
                }
            },
            backBtn() {
                this.saveVisible = false;
                this.searchForm.items = []
                this.fileTypeNameData = []
                this.$emit('closepop');
            },
            changePage(v) {
                this.loanBackReasonParams.pageNumber = v
                this.getBackPartnersList()
            },
            changePageSize(v) {
                this.loanBackReasonParams.pageSize = v
                this.getBackPartnersList()
            },
            setblue() {
                this.$refs.backWordsSelect.blur();
            },
            changeBackWords(value, index) {
                let backWord = '';
                let backWordsList = '';
                value.forEach(function (e) {
                    backWord += e.split(',')[1] + '。';
                    backWordsList += e + ';';
                });
                this.searchForm.items[index].backDesc = backWordsList;
                this.searchForm.items[index].backWords = backWord;
            },
            submitCheck() {
                this.spinShow = true;
                let params = true;
                this.searchForm.items.forEach(item => {
                    if (item.fileType != undefined && item.fileType != null && item.fileType != '' &&
                        item.backWords != undefined && item.backWords != null && item.backWords != '') {
                        item.applyNo = this.loanBackReasonParams.applyNo;
                        item.contractNo = this.loanBackReasonParams.contractNo;
                        item.taskId = this.loanBackReasonParams.taskId;
                    } else {
                        params = false;
                    }
                })
                if (params) {
                    this.$refs.searchForm.validate(valid => {
                        if (valid) {
                            this.submitBackToPartners()
                        }
                    })
                } else {
                    this.$Message.warning("包含未选择的文件类型，未填写的退回话术！")
                    this.saveVisible = false;
                    this.spinShow = false;
                }
            },
            submitBackToPartners() {
                saveOrUpdateBackResonList(this.searchForm.items).then(res=>{
                    console.info("批量保存数据"+res);
                    if(res.code ==="0000"){
                        submitBackToPartners(this.loanBackReasonParams).then(res=>{
                            if(res.code =="0000"){
                                this.$Message.success('提交成功')
                            }
                            this.saveVisible = false;
                            this.spinShow = false;
                            this.$emit('closepop');
                            this.$emit("backBtn");
                        });
                    }
                });
            }
        }
    }
</script>

<style scoped>
    /deep/ .ivu-modal-body {
        padding: 16px;
        font-size: 12px;
        line-height: 1.5;
        height: 400px;
        overflow-x: hidden;
        overflow-y: auto;
    }

</style>
